package com.tt.utils;

import java.util.Random;

/**
 * @Title: VerificationCodeUtil
 * @Author zl
 * @Package com.tt.utils
 * @Date 2025/6/24 11:27
 * @description: 随机生成工具类
 */
public class VerificationCodeUtil {

    // 定义所有可能的字符（数字+大写字母+小写字母）
    private static final String CHAR_SET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    // 仅数字的字符集
    private static final String NUMERIC_SET = "0123456789";

    /**
     * 生成随机6位验证码（包含数字和字母）
     * @return 6位随机验证码字符串
     */
    public static String generateRandomCode() {
        return generateRandomCode(6, false);
    }

    /**
     * 生成纯数字的6位验证码
     * @return 6位数字验证码字符串
     */
    public static String generateNumericCode() {
        return generateRandomCode(6, true);
    }

    /**
     * 生成指定长度的随机验证码
     * @param length 验证码长度
     * @param numericOnly 是否仅为数字
     * @return 随机验证码字符串
     */
    public static String generateRandomCode(int length, boolean numericOnly) {
        if (length <= 0) {
            throw new IllegalArgumentException("验证码长度必须大于0");
        }

        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);
        String source = numericOnly ? NUMERIC_SET : CHAR_SET;

        for (int i = 0; i < length; i++) {
            int index = random.nextInt(source.length());
            sb.append(source.charAt(index));
        }

        return sb.toString();
    }

    // 测试
    public static void main(String[] args) {
        System.out.println("6位数字验证码: " + generateNumericCode());
        System.out.println("6位混合验证码: " + generateRandomCode());
        System.out.println("8位混合验证码: " + generateRandomCode(8, false));
        System.out.println("4位数字验证码: " + generateRandomCode(4, true));
    }
}
